import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/eventbus/EventRefreshPart.dart';
import 'package:yuellyfactory/util/BaseRequest.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';
import 'package:yuellyfactory/views/dto/PriceParm.dart';

import '../../components/NoScrollbarBehavior.dart';
import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/ColorUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';


class RuleVC extends StatefulWidget {
  final VoidCallback callback;
  final PricePart pricePart;
  const RuleVC({super.key, required this.callback, required this.pricePart});

  @override
  State<RuleVC> createState() => _RuleVCState();
}

class _RuleVCState extends State<RuleVC> {


  final popoverController = ShadPopoverController();

  List<PriceRule> rules=[];
  Map idNams={};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getAllParms();
  }

  @override
  Widget build(BuildContext context) {
    return ShadSheet(

      onClosing: (){
        widget.callback();
      },
      constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),

      title: Row(
        children: [
          const Text('计算公式'),
          const SizedBox(width: 50,),
          ViewUtil.doneIcon("保存", (){
            submit();
          })
        ],
      ),
      description: const Text(
          "请编辑单价计算公式"),
      child:

          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [

              Row(
                children: [
                  ShadPopover(
                    controller: popoverController,
                    popover: (context) => _buildPopoverContent(),

                    child: ViewUtil.textButton(
                      '新增',
                      20,
                      15,
                      ViewUtil.radio(15),
                      ColorUtil.colorBlue,
                      ColorUtil.colorBlue,
                      Colors.white,
                      ViewUtil.fontSize(20),
                          () {
                        popoverController.show();
                      },
                    ),
                  ),
                  const SizedBox(width: 20,),

                  // ViewUtil.textButton(
                  //   '保存',
                  //   20,
                  //   15,
                  //   ViewUtil.radio(15),
                  //   ColorUtil.colorBlue,
                  //   ColorUtil.colorBlue,
                  //   Colors.white,
                  //   ViewUtil.fontSize(20),
                  //       () {
                  //         submit();
                  //   },
                  // )
                ],
              ),

              ScrollConfiguration(
                behavior: NoScrollbarBehavior(),
                child: SingleChildScrollView(
                  child:
                  Padding(
                    padding: const EdgeInsets.all(5.0),
                    child:
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: getAllWidget(),
                    )
                    ,
                  ),),
              )
            ],
          )

     ,
    );
  }


  List<Widget> getAllWidget(){
    List<Widget> views=[];

    for(var i=0;i<rules.length;i++){
      PriceRule priceRule=rules[i];
      if(priceRule.handle==0){
        views.add(const SizedBox(height: 10,));
        views.add(
          KeyedSubtree(
            key: ValueKey(priceRule), // 关键：添加唯一Key
            child: inputWidget(priceRule, i),
          ),
        );
      }else{
        views.add(const SizedBox(height: 10,));
        views.add(
          KeyedSubtree(
            key: ValueKey(priceRule), // 关键：添加唯一Key
            child: selectWidget(priceRule, i),
          ),
        );
      }
    }

    return views;
  }


  Widget selectWidget(PriceRule rule,int position) {
    return Row(
      // 让Row占满父级宽度
      mainAxisSize: MainAxisSize.max,
      children: [
        // 用Expanded让输入框填充Row的可用空间
        Expanded(
          flex: 1,
          child:ShadSelectFormField<String>(

            onChanged: (value){
              debugPrint(value);
              rule.value=value!;
            },
            minWidth: 800,
            initialValue: rule.value,
            options: (idNams).entries
                .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                .toList(), // 注意添加toList()转换
            selectedOptionBuilder: (context, value) {
              if (value == null || value == 'none') {
                return const Text('请选择零件');
              }
              // 使用空值合并运算符??代替!，提供默认值
              return Text((idNams)[value]?.toString() ?? '请选择');
            },

            validator: (v) {
              if (v == null) {
                return '请选择';
              }
              return null;
            },
          ),
        ),
        Expanded(
            flex: 1,
            child: Row(
              children: [
                ShadButton.destructive(
                  child: const Text('删除'),
                  onPressed: () {
                    rules.removeAt(position);
                    setState(() {

                    });
                  },
                ),
                Visibility(
                    visible: position!=0,
                    child: ShadButton(
                  child: const Text('上移'),
                  onPressed: () {
                    moveUp(position);

                  },
                ))
                ,
                Visibility(
                    visible: position!=rules.length-1,
                    child: ShadButton(
                  child: const Text('下移'),
                  onPressed: () {
                    moveDown(position);
                  },
                ))
                ,
              ],

            ))
      ],
    );
  }



  Widget inputWidget(PriceRule rule,int position) {
    return Row(
      // 让Row占满父级宽度
      mainAxisSize: MainAxisSize.max,
      children: [
        // 用Expanded让输入框填充Row的可用空间
        Expanded(
          flex: 1,
          child: ShadInputFormField(
            initialValue: rule.value,
            placeholder: const Text('请输入'),
            // 给输入框添加最小宽度约束（可选）
            validator: (v) {
              if (v == null || v.isEmpty) { // 注意处理null情况
                return '请输入';
              }
              return null;
            },
            onChanged: (value) {
              rule.value = value ?? ''; // 处理null情况
            },
          ),
        ),
        Expanded(
            flex: 1,
            child: Row(
              children: [
                ShadButton.destructive(
                  child: const Text('删除'),
                  onPressed: () {
                    rules.removeAt(position);
                    setState(() {

                    });
                  },
                ),
                Visibility(
                    visible: position!=0,
                    child: ShadButton(
                      child: const Text('上移'),
                      onPressed: () {
                        moveUp(position);

                      },
                    ))
                ,
                Visibility(
                    visible: position!=rules.length-1,
                    child: ShadButton(
                      child: const Text('下移'),
                      onPressed: () {
                        moveDown(position);
                      },
                    ))
                ,
              ],

            ))
      ],
    );
  }

  // 上移操作
  void moveUp(int index) {
    if (index <= 0) return; // 已经是第一个元素，不能上移

    setState(() {
      // 交换当前元素和前一个元素的位置
      PriceRule temp = rules[index];
      rules[index] = rules[index - 1];
      rules[index - 1] = temp;
    });
  }

  // 下移操作
  void moveDown(int index) {
    if (index >= rules.length - 1) return; // 已经是最后一个元素，不能下移
    setState(() {
      // 交换当前元素和后一个元素的位置
      PriceRule temp = rules[index];
      rules[index] = rules[index + 1];
      rules[index + 1] = temp;
    });
  }


  addInput(){
    PriceRule priceRule=PriceRule();
    priceRule.handle=0;
    rules.add(priceRule);
    setState(() {

    });
  }
  addSelect(){
    PriceRule priceRule=PriceRule();
    priceRule.handle=1;
    rules.add(priceRule);
    setState(() {

    });
  }



  Widget _buildPopoverContent() {
    return SizedBox(
      width: 100,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '请选择录入方式',

          ),

          const SizedBox(height: 4),
          ShadButton.outline(
            onPressed:(){
              debugPrint('录入数据');
              addInput();
              popoverController.hide();
            },
            child: const Text('录入数据'),
          ),
          const SizedBox(height: 4),
          ShadButton.outline(
            onPressed:(){
              debugPrint('选择参数');
              addSelect();
              popoverController.hide();
            },
            child: const Text('选择参数'),
          )

        ],
      ),
    );
  }


  void getAllParms(){
    var parm={
      "id":widget.pricePart.id,
    };

    BaseRequest.postHttp('price/getallparam',parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        List allParms=[];
        for(var i=0;i<datas.length;i++){
          var item=datas[i];
          var part=PriceParm.fromJson(item);
          idNams[part.id]=part.name;
          allParms.add(part);
        }

      }
      initDatas();

    }, onError: (error){


    });
  }

  void submit(){
    bool result=true;
    List datas=[];
    for(PriceRule parm in rules){
      if(parm.value.isEmpty){

        if(parm.handle==0){
          ToastUtil.showToast("请输入");
        }else{
          ToastUtil.showToast("请选择");
        }
        result=false;
        break;
      }
      if(parm.handle==1){
        parm.name=idNams[parm.value];
      }
      datas.add(parm.toJson());
    }
    if(!result){
      return;

    }
    var parm={
      "id":widget.pricePart.id,
      "rule":datas
    };
    BaseRequest.postHttp('price/savepartrule',parameters: parm, canTip: true, context: context, onSuccess: (data){
      if(result){
        ToastUtil.showToast("编辑成功");
        eventBus.fire(EventRefreshPart());
        Navigator.pop(context);
      }
    }, onError: (error){

    });

  }
  void initDatas(){
    if(widget.pricePart.rule.isNotEmpty){
      List<dynamic> list = json.decode(widget.pricePart.rule);
      List<PriceRule> ruleList=[];
      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        ruleList.add(rule);
      }
      rules=ruleList;
      setState(() {

      });
    }
  }
}
